<?php
class CacheMem{
	private static $cacher = null;
	private $memcacher;
    private $outTime;
    private $pre;
	private function __construct($conf){
//        $conf=[
//            "type"=>"mem",
//            "host"=>"127.0.0.1",
//            "port"=>"11211",
//            "pre"=>"mtfy_",
//            "outtime"=>40,
//        ];
		$this->memcacher = new \Memcache();
		$this->memcacher->connect($conf['host'], $conf['port']);
		$this->pre = $conf['pre'];
        $this->outTime=@$conf["outtime"]?$conf["outtime"]:3600;
	}

	public static function new($conf){
        if(!$conf){
            $conf=".cache";
        }
        if(function_exists("Config")){
            $conf=Config($conf);
        }else{
            throw new Exception("缓存配置错误");
        }
		if(self::$cacher == null){self::$cacher = new CacheMem($conf);}
		return self::$cacher;
	}
    public static function newc($conf){
        if(self::$cacher == null){self::$cacher = new CacheMem($conf);}
        return self::$cacher;
    }

	public function get($name){
		return $this->memcacher->get($this->pre.$name);
	}

	public function set($name, $val, $expire = null){
        if(!$expire){
            $expire=$this->outTime;
        }
        if($val===null){
            $this->remove($name);
            return;
        }
		if($expire > 2592000){$expire = 2592000;}
		$this->memcacher->set($this->pre.$name, $val, MEMCACHE_COMPRESSED, $expire);
	}

	public function remove($name){
		$this->memcacher->delete($this->pre.$name);
	}

	public function clear(){
		$this->memcacher->flush();
	}

	public function close(){
		$this->memcacher->close();
	}
}